package com.beiding.codecreater.core.render;

import com.beiding.codecreater.utils.ContentUtils;
import com.beiding.codecreater.utils.FileUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

//模板编译器
public class TemplateCompiler {

    private String blockStartTagName = "block";
    private String blockEndTagName = "block";

    private String renderStartTagName = "render";
    private String renderEndTagName = "render";


    private URepeatBlock uRepeatBlock;
    private URender uValue;

    private String nullText = "";

    public void setNullText(String nullText) {
        this.nullText = nullText;
    }

    public Template compile(InputStream inputStream) throws IOException {
        String s = FileUtils.readInputStreamAsString(inputStream);
        return compile(s);
    }
        //进行编译操作
    public Template compile(String text) {

        if (uRepeatBlock == null || uValue == null) {
            this.uRepeatBlock = new URepeatBlock(blockStartTagName, blockEndTagName);
            uValue = new URender(renderStartTagName, renderEndTagName);
        }

        if (ContentUtils.isEmpty(text)) {
            throw new RuntimeException("文本不能为空");
        }
        List<URepeatBlock.Pair> pairs = uRepeatBlock.parsePairs(text);

        //处理成树状结构
        uRepeatBlock.pairToTree(pairs);
        return Template.create(text, pairs,uRepeatBlock,uValue,nullText);
    }

    public String getBlockStartTagName() {
        return blockStartTagName;
    }

    public void setBlockStartTagName(String blockStartTagName) {
        this.blockStartTagName = blockStartTagName;
    }

    public String getBlockEndTagName() {
        return blockEndTagName;
    }

    public void setBlockEndTagName(String blockEndTagName) {
        this.blockEndTagName = blockEndTagName;
    }

    public String getRenderStartTagName() {
        return renderStartTagName;
    }

    public void setRenderStartTagName(String renderStartTagName) {
        this.renderStartTagName = renderStartTagName;
    }

    public String getRenderEndTagName() {
        return renderEndTagName;
    }

    public void setRenderEndTagName(String renderEndTagName) {
        this.renderEndTagName = renderEndTagName;
    }
}
